﻿@using PMS.Data.Entities.Customers
@using PMS.Web.FrontUI
@using PMS.Web.Models.Customers
@using PMS.Web.Models.Medias
@model CustomerModel
@{
    Layout = "_AdminHomeLayout";
    List<ExternalAuthenticationRecord> allExternalRecords = ViewBag.AllExternalRecords as List<ExternalAuthenticationRecord> ?? null;
    List<ExternalAuthenticationMethodModel> authenticationMethodList = ViewBag.ExternalAuthenticationMethodModel as List<ExternalAuthenticationMethodModel> ?? null;
    MediaUploadRequsetModel AvatarUploadModel = ViewBag.AvatarUploadModel as MediaUploadRequsetModel ?? null;
}

@section CssStyles{
    <style type="text/css">
        /* 用户信息 */
        .user-info-head {
            width: 110px;
            height: 110px;
            line-height: 110px;
            position: relative;
            display: inline-block;
            border: 2px solid #eee;
            border-radius: 50%;
            overflow: hidden;
            cursor: pointer;
            margin: 0 auto;
        }

        .user-info-head:hover:after {
            content: '\e681';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            color: #fff;
            background-color: rgba(0, 0, 0, 0.3);
            font-size: 28px;
            padding-top: 2px;
            font-style: normal;
            font-family: layui-icon;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
        }

        .user-info-head img {
            width: 110px;
            height: 110px;
        }

        .user-info-list-item {
            position: relative;
            padding-bottom: 8px;
        }

        .user-info-list-item > .layui-icon {
            position: absolute;
        }

        .user-info-list-item > p {
            padding-left: 30px;
        }

        .layui-line-dash {
            border-bottom: 1px dashed #ccc;
            margin: 15px 0;
        }

        /* 基本信息 */
        #userInfoForm .layui-form-item {
            margin-bottom: 25px;
        }

        /* 账号绑定 */
        .user-bd-list-item {
            padding: 14px 60px 14px 10px;
            border-bottom: 1px solid #e8e8e8;
            position: relative;
        }

        .user-bd-list-item .user-bd-list-lable {
            color: #333;
            margin-bottom: 4px;
        }

        .user-bd-list-item .user-bd-list-oper {
            position: absolute;
            top: 50%;
            right: 10px;
            margin-top: -8px;
            cursor: pointer;
        }

        .user-bd-list-item .user-bd-list-img {
            width: 48px;
            height: 48px;
            line-height: 48px;
            position: absolute;
            top: 50%;
            left: 10px;
            margin-top: -24px;
        }

        .user-bd-list-item .user-bd-list-img + .user-bd-list-content {
            margin-left: 68px;
        }

        .layui-form-item .layui-input-inline {
            width: 268px;
        }

        .layui-layer .layui-form-label {
            width: 95px;
        }
    </style>
}

<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <!-- 左 -->
        <div class="layui-col-sm12 layui-col-md3">
            <div class="layui-card">
                <div class="layui-card-body" style="padding: 25px;">
                    <div class="text-center layui-text">
                        <div class="user-info-head" id="userHeadInfo">
                            <img src="@Model.AvatarImage.ImageUrl" alt="@AvatarUploadModel.Title" id="userAvatarImage">
                        </div>
                        <input type="file" accept=".gif,.jpg,.jpeg,.png" id="avatarInput" class="layui-hide" />
                        <h2 style="padding-top: 20px;">@(string.IsNullOrEmpty(Model.NickName) ? Model.DisplayName(m => m.NickName) : Model.NickName)</h2>
                        <p style="padding-top: 8px;">@(string.IsNullOrEmpty(Model.Email) ? "未绑定邮箱" : Model.Email)</p>
                        <p style="padding-top: 8px;">@Model.Mobile</p>
                    </div>
                    <div class="layui-text" style="padding-top: 30px;">
                        <div class="user-info-list-item">
                            <i class="layui-icon layui-icon-username"></i>
                            <p>@(string.IsNullOrEmpty(Model.LoginName) ? Model.DisplayName(m => m.LoginName) : Model.LoginName)</p>
                        </div>
                        <div class="user-info-list-item">
                            <i class="layui-icon @(Model.Gender == "男" ? "layui-icon-male" : "layui-icon-female")"></i>
                            <p>@(string.IsNullOrEmpty(Model.Gender) ? Model.DisplayName(m => m.Gender) : Model.Gender)</p>
                        </div>
                        <div class="user-info-list-item">
                            <i class="layui-icon layui-icon-gift"></i>
                            <p>@(Model.DateOfBirth.HasValue ? Model.DateOfBirth.Value.ToString("yyyy-MM-dd") : Model.DisplayName(m => m.DateOfBirth))</p>
                        </div>
                        <div class="user-info-list-item">
                            <i class="layui-icon layui-icon-user"></i>
                            <p>@(string.IsNullOrEmpty(Model.CustomerRoleNames) ? Model.DisplayName(m => m.CustomerRoleNames) : Model.CustomerRoleNames)</p>
                        </div>
                    </div>
                    <div class="layui-line-dash"></div>
                    <h3>最近访问</h3>
                    <div class="layui-text">
                        <div class="user-info-list-item">
                            <i class="layui-icon layui-icon-time"></i>
                            <p>@(Model.LastActivityTime == null ? Model.DisplayName(m => m.LastActivityTime) : Model.LastActivityTime.ToString("yyyy-MM-dd HH:mm"))</p>
                        </div>
                        <div class="user-info-list-item">
                            <i class="layui-icon layui-icon-location"></i>
                            <p>@(string.IsNullOrEmpty(Model.LastLoginIpAddress) ? Model.DisplayName(m => m.LastLoginIpAddress) : Model.LastLoginIpAddress)</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!-- 右 -->
        <div class="layui-col-sm12 layui-col-md9">
            <div class="layui-card">
                <!-- 选项卡开始 -->
                <div class="layui-tab layui-tab-brief" lay-filter="userInfoTab">
                    <ul class="layui-tab-title">
                        <li class="layui-this">基本信息</li>
                        <li>账号绑定</li>
                    </ul>
                    <div class="layui-tab-content">
                        <!-- tab1 -->
                        <div class="layui-tab-item layui-show">
                            <form class="layui-form" id="userInfoForm" lay-filter="userInfoForm" style="max-width: 800px;padding: 25px 10px 0 0;">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">@Model.DisplayName(m => m.Email)</label>
                                    <div class="layui-input-inline">
                                        <input type="text" name="@Model.NameOf(m => m.Email)" value="@(string.IsNullOrEmpty(Model.Email) ? "" : Model.Email)" placeholder="通过[账号绑定]绑定更改邮箱" autocomplete="off" class="layui-input" />
                                    </div>
                                    <div class="layui-form-mid layui-word-aux">不可编辑,修改无效,请通过账号绑定更改</div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">@Model.DisplayName(m => m.Mobile)</label>
                                    <div class="layui-input-inline">
                                        <input type="text" name="@Model.NameOf(m => m.Mobile)" value="@(string.IsNullOrEmpty(Model.Mobile) ? "" : Model.Mobile)" placeholder="通过[账号绑定]绑定更改手机号码" autocomplete="off" class="layui-input" />
                                    </div>
                                    <div class="layui-form-mid layui-word-aux">不可编辑,修改无效,请通过账号绑定更改</div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">@Model.DisplayName(m => m.LoginName)</label>
                                    <div class="layui-input-inline">
                                        <input type="text" name="@Model.NameOf(m => m.LoginName)" value="@Model.LoginName" placeholder="以字母开头的字母数字组合，且长度为3-20位" autocomplete="off" class="layui-input" />
                                    </div>
                                    <div class="layui-form-mid layui-word-aux">不可编辑,修改无效,请通过账号绑定更改</div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">@Model.DisplayName(m => m.NickName)</label>
                                    <div class="layui-input-inline">
                                        <input type="text" name="@Model.NameOf(m => m.NickName)" value="@Model.NickName" lay-verify="required" placeholder="请输入用户昵称" autocomplete="off" class="layui-input" />
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">@Model.DisplayName(m => m.Gender)</label>
                                    <div class="layui-input-block">
                                        <input type="radio" name="@Model.NameOf(m => m.Gender)" value="男" title="男" @if (Model.Gender == "男") { <text> checked </text> }>
                                        <input type="radio" name="@Model.NameOf(m => m.Gender)" value="女" title="女" @if (Model.Gender == "女") { <text> checked </text> }>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">@Model.DisplayName(m => m.DateOfBirth)</label>
                                    <div class="layui-input-inline">
                                        <input type="text" id="birthDay" name="@Model.NameOf(m => m.DateOfBirth)" value="@(Model.DateOfBirth.HasValue ? Model.DateOfBirth.Value.ToString("yyyy-MM-dd") : "")" autocomplete="off" class="layui-input" />
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">@Model.DisplayName(m => m.DefaultAddress)</label>
                                    <div class="layui-input-inline">
                                        <div id="areaSelect"></div>
                                        <input type="text" name="@Model.NameOf(m => m.DefaultAddress)" value="@((Model.DefaultAddress?.Count ?? 0) > 0 ? (string.Join(",", Model.DefaultAddress)) : "")" autocomplete="off" class="layui-input layui-hide" />
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label"></label>
                                    <div class="layui-input-inline">
                                        <input type="text" name="@Model.NameOf(m => m.DefaultAddressDetail)" value="@Model.DefaultAddressDetail" placeholder="请输入详细地址" autocomplete="off" class="layui-input" />
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">@Model.DisplayName(m => m.Password)</label>
                                    <div class="layui-input-inline">
                                        <input type="password" name="@Model.NameOf(m => m.Password)" value="" @if (Model.Id == 0) { <text> lay-verify="required" </text> } placeholder="请输入账户密码" autocomplete="off" class="layui-input" />
                                        <input type="text" class="layui-hide" name="@Model.NameOf(m => m.PasswordStrongLevel)" value="" />
                                    </div>
                                    <div class="layui-form-mid layui-word-aux">仅当修改账号密码时填写</div>
                                </div>
                                <input type="text" name="@Model.NameOf(m => m.Id)" value="@Model.Id" class="layui-hide" />
                                <input type="text" name="@Model.NameOf(m => m.AllowReSendingOfActivationMessage)" value="true" class="layui-hide" />
                                <input type="text" name="@Model.NameOf(m => m.IsActive)" value="@Model.IsActive.ToString()" class="layui-hide" />
                                <input type="text" name="AvatarImage.Id" value="@Model.AvatarImage.Id.ToString()" class="layui-hide" />
                                <div class="layui-form-item">
                                    <div class="layui-input-block">
                                        <button type="button" id="userInfoSubmitBtn" class="pear-btn pear-btn-primary pear-btn-sm" lay-filter="userInfoSubmit" lay-submit="">
                                            更新基本信息[保存]
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>
                        <!-- tab1 -->
                        <div class="layui-tab-item" style="padding-bottom: 20px;">
                            <div class="user-bd-list layui-text">
                                <div class="user-bd-list-item">
                                    <div class="user-bd-list-lable">密保手机</div>
                                    <div class="user-bd-list-text">@(string.IsNullOrEmpty(Model.Mobile) ? "未绑定手机" : $"已绑定手机：{Html.HideMobile(Model.Mobile)}")</div>
                                    <a class="user-bd-list-oper" id="bindMobile">修改</a>
                                </div>
                                <div class="user-bd-list-item">
                                    <div class="user-bd-list-lable">密保邮箱</div>
                                    <div class="user-bd-list-text">@(string.IsNullOrEmpty(Model.Email) ? "未绑定邮箱" : $"已绑定邮箱：{Html.HideEmail(Model.Email)}")</div>
                                    <a class="user-bd-list-oper" id="bindEmail">修改</a>
                                </div>
                                <div class="user-bd-list-item">
                                    <div class="user-bd-list-lable">登录账号</div>
                                    <div class="user-bd-list-text">@(string.IsNullOrEmpty(Model.LoginName) ? "未绑定账号" : $"已绑定：{Model.LoginName}")</div>
                                    <a class="user-bd-list-oper" id="bindLoginname">修改</a>
                                </div>

                                @foreach (var authenticationMethod in authenticationMethodList)
                                {
                                    <div class="user-bd-list-item">
                                        <div class="user-bd-list-img">
                                            @await Component.InvokeAsync(authenticationMethod.ViewComponentName, new { widgetZone = "BindAccount" })
                                        </div>
                                        <div class="user-bd-list-content">
                                            <div class="user-bd-list-lable">@(string.IsNullOrEmpty(authenticationMethod.DisplayName) ? "绑定账号" : $"绑定{authenticationMethod.DisplayName}" )</div>
                                            <div class="user-bd-list-text">@(allExternalRecords != null && allExternalRecords.Any(er => er.ProviderSystemName.Equals(authenticationMethod.ProviderSystemName, StringComparison.CurrentCultureIgnoreCase)) ? "账号已绑定" : "账号还未绑定")</div>
                                        </div>
                                        <a class="user-bd-list-oper externalAccountBind">绑定</a>
                                    </div>

                                }
                            </div>
                        </div>
                    </div>
                </div>
                <!-- //选项卡结束 -->
            </div>
        </div>
    </div>
</div>

@await Component.InvokeAsync("ModelValidateError")
@section Scripts{
    <script src="~/lib/ipicker/dist/iPicker.min.js" asp-append-version="true"></script>
    <script src="~/dist/js/utils/passwordstrength.min.js" asp-append-version="true"></script>
    <script type="text/javascript">
        layui.use(['jquery', 'form', 'element', 'lodash', 'laydate', 'http', 'button', 'laytpl', 'popup'], function () {
            var $ = layui.jquery,
                form = layui.form,
                element = layui.element,
                lodash = layui.lodash,
                laydate = layui.laydate,
                http = layui.http,
                button = layui.button,
                laytpl = layui.laytpl,
                popup = layui.popup;

            var userInfoPage = {
                getAreaJson: function () {
                    return new Promise(function (resolve) {
                        http.get(backendwebapiConfig.getareadatajson, null)
                            .then(function (response) {
                                if (response.state && response.state === 200) {
                                    resolve(response.data);
                                }
                            });
                    });
                },
                avatarRequest: @Html.Convert2JavascriptJsonString(AvatarUploadModel, false)
                , bindAvatarUploadEvent: function () {
                    var self = this;
                    $("#userHeadInfo").on("click", function () {
                        $("#avatarInput").click();
                    });
                    $("#avatarInput").on("change", function () {
                        // Image Preview
                        const files = this.files[0]; //files[0] - For getting first file
                        if (files) {
                            //Read File
                            const fileReader = new FileReader();
                            fileReader.addEventListener("load", function () {
                                // convert image to base64 encoded string
                                $("#userAvatarImage").attr("src", this.result);
                            });
                            fileReader.readAsDataURL(files);
                            self.avatarRequest.File = files;
                            var avatarId = PMSUtils.toInteger($("input[name=AvatarId]").val());
                            if (self.avatarRequest.Id !== avatarId) {
                                self.avatarRequest.Id = avatarId;
                            }
                            var formData = new FormData();
                            //参数封装至FormData
                            layui.each(self.avatarRequest, function (key, value) {
                                value = typeof value === 'function' ? value() : value;
                                formData.append(key, value);
                            });
                            http.postForm(backendwebapiConfig.commonuploadapi, formData, null).done(
                                function (response) {
                                    if (response.state && response.state === 200) {
                                        //upload api respond data as: {Id: mediaFileId, VirtualPath: mediaFileUrl}
                                        popup.success("头像上传成功,记得点击保存以保存用户头像", function () {
                                            self.avatarRequest.Id = response.data.Id;
                                            var avatarImgUrl = response.data.VirtualPath + "?t=" + new Date().getTime();
                                            $("#userAvatarImage").attr("src", avatarImgUrl);
                                            $("input[name=AvatarId]").val(response.data.Id);
                                        });
                                    }
                                }
                            );
                        }
                    });
                },
                initPageComponent: function () {
                    var self = this;
                    self.bindAvatarUploadEvent();
                    //生日日期选择
                    laydate.render({
                        elem: '#birthDay'
                        , type: 'date'
                    });
                    //AreaSelect
                    iPicker.create("#areaSelect", {
                        theme: "cascader",
                        data: {
                            source: self.getAreaJson()
                        },
                        width: 268,
                        icon: "arrow-outline",
                        strict: true,
                        selected: lodash.split($("input[name=DefaultAddress]").val(), ","),
                        onSelect(code, name, map) {
                            $("input[name=DefaultAddress]").val(lodash.join(code, ','));
                        }
                    });

                    //force avatarUrl refresh
                    var timestamp = new Date().getTime();
                    var avatarImgUrl = $("#userAvatarImage").attr("src") + "?t=" + timestamp;
                    $("#userAvatarImage").attr("src", avatarImgUrl);
                    
                    form.on('submit(userInfoSubmit)', function (data) {
                        var submitUserInfo = function (userInfo) {
                            if (userInfo.DefaultAddress.length > 0 && PMSUtils.gettype(userInfo.DefaultAddress) === 'string') {
                                userInfo.DefaultAddress = lodash.split(userInfo.DefaultAddress, ',');
                            } else {
                                userInfo.DefaultAddress = null;
                            }
                            if (userInfo.Password.length <= 0 && userInfo.AllowReSendingOfActivationMessage) {
                                //勾选时 AllowReSendingOfActivationMessage 相应有值
                                //借用 Model.AllowReSendingOfActivationMessage 存储当修改账号密码时，是否发送重置密码邮件
                                //勾选重置账号密码但未输入重置密码，则无需发送邮件
                                userInfo.AllowReSendingOfActivationMessage = false;
                            } else if (userInfo.Password.length > 0) {
                                var strength = PasswordStrength.test(userInfo.LoginName, userInfo.Password);
                                if (strength.isGood()) {
                                    userInfo.PasswordStrongLevel = "Good";
                                } else if (strength.isStrong()) {
                                    userInfo.PasswordStrongLevel = "Strong";
                                } else {
                                    userInfo.PasswordStrongLevel = "Weak";
                                }
                            }

                            var loadbtn = null;
                            http.post(backendwebapiConfig.customeredit, userInfo,
                                function () { //beforeSend
                                    loadbtn = button.load({
                                        elem: '#userInfoSubmitBtn',
                                        time: 10000
                                    });
                                }
                            ).done(function (response) {
                                if (response.state && response.state === 200) {
                                    popup.success(response.message, function () {
                                        //window.location.reload(true);
                                        window.top.location.reload(true);
                                    });
                                }
                            }).fail(function (error) {
                                //For ModelValidation
                                if (error.status && error.status === 400) {
                                    var validator = error.responseJSON;
                                    if (validator.ErrorCode && validator.ErrorCode === "FluentValidationError") {
                                        var validateTpl = document.getElementById('validateResultTpl').innerHTML;
                                        laytpl(validateTpl).render(validator, function (html) {
                                            http.ajax.showError({
                                                message: '提示信息',
                                                details: html
                                            });
                                        });
                                        //标红校验错误的数据框
                                        layui.each(validator.Errors, function (index, item) {
                                            var inputField = item.ErrorField;
                                            $("input[name=" + inputField + "]").attr('failure', '');
                                        });
                                    }
                                }
                            }).always(function () {
                                loadbtn.stop(function () { });
                            });
                        };
                        var postData = data.field;
                        if (postData.Password.length > 0 && postData.Id > 0) {
                            layer.confirm('您确定要重置该账号密码吗?', { icon: 3, title: '提示' }, function (index) {
                                //do something
                                submitUserInfo(postData);
                                layer.close(index);
                            });
                            return false;
                        }

                        submitUserInfo(postData);
                        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
                    });
                },
            };

            var popupWindowConfig = {
                title: "",
                type: 2,
                content: bakcendviewConfig.customerchangeaccountview,
                iframeAuto: true,
                anim: 3,
                end: function () {
                    window.location.reload(true);
                }
            };
            var accountBindPage = {
                bindMobile: function () {
                    $("#bindMobile").on("click", function () {
                        popupWindowConfig.title = "绑定手机号码";
                        popupWindowConfig.content = bakcendviewConfig.customerchangeaccountview + "?mode=MobilePhone";
                        PMSUtils.popupWindow(popupWindowConfig);
                    });
                },
                bindEmail: function () {
                    $("#bindEmail").on("click", function () {
                        popupWindowConfig.title = "绑定账号邮箱";
                        popupWindowConfig.content = bakcendviewConfig.customerchangeaccountview + "?mode=Email";
                        PMSUtils.popupWindow(popupWindowConfig);
                    });
                },
                bindLoginName: function () {
                    $("#bindLoginname").on("click", function () {
                        popupWindowConfig.title = "绑定登录账号";
                        popupWindowConfig.content = bakcendviewConfig.customerchangeaccountview + "?mode=LoginName";
                        PMSUtils.popupWindow(popupWindowConfig);
                    });
                },
                externalAccountBind: function () {
                    $(".externalAccountBind").each(function () {
                        var $a = $(this).parents(".user-bd-list-item").find(".user-bd-list-img > a");
                        if ($a.length > 0) {
                            var authUrl = $a.attr("href");
                            $a.attr("href", "javascript:;");
                            $(this).on("click", function () {
                                PMSUtils.redirect(authUrl, false);
                            });
                        }
                    });
                },

                initPageComponent: function () {
                    this.externalAccountBind();
                    this.bindMobile();
                    this.bindEmail();
                    this.bindLoginName();
                },
            };

            userInfoPage.initPageComponent();
            accountBindPage.initPageComponent();
        });
    </script>
}
